package com.xcalendar.database.dao;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.xcalendar.database.persistence.PMF;
import com.xcalendar.database.table.User;

public class UserDAO {

	public void addUser(User user) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction txn = pm.currentTransaction();
		try {
			txn.begin();
			Key key = KeyFactory.createKey(User.class.getSimpleName(), user.getUserName());
			user.setKey(key);
			pm.makePersistent(user);
			txn.commit();
		} finally {
			if (txn.isActive()) {
				txn.rollback();
			}
			pm.close();
		}
	}

	public User readUser(User user) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		User gottenUser;
		try {
			Key k = KeyFactory.createKey(User.class.getSimpleName(),
					user.getUserName());
			gottenUser = pm.getObjectById(User.class, k);
		} catch (JDOObjectNotFoundException e) {
			gottenUser = null;
		} finally {
			pm.close();
		}
		return gottenUser;
	}

	public void deleteUser(User user) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction txn = pm.currentTransaction();
		try {
			txn.begin();
			user = pm.getObjectById(User.class, user.getKey());
			pm.deletePersistent(user);
			txn.commit();
		} catch (Exception e) {
			txn.rollback();
		} finally {
			pm.close();
		}
	}

	public void updateUserRegisterId(User user) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction txn = pm.currentTransaction();
		String registrationID = user.getRegistrationID();
		try {
			txn.begin();
			Key k = KeyFactory.createKey(User.class.getSimpleName(),
					user.getUserName());
			user = pm.getObjectById(User.class, k);
			user.setRegistrationID(registrationID);
			pm.makePersistent(user);
			txn.commit();
		} finally {
			if (txn.isActive()) {
				txn.rollback();
			}
			pm.close();
		}
	}

}
